package mysql

import (
	"shuqi-novel/shuqirpc/shuqirpc"

	"gorm.io/gorm"
)

type Novel struct {
	gorm.Model
	Title   string `gorm:"type:varchar(30);not null;comment:'标题'"`
	Content string `gorm:"type:text;not null;comment:'内容'"`
	Class   string `gorm:"type:varchar(30);not null;comment:'分类'"`
	UserId  int64  `gorm:"type:int(11);not null;comment:'用户ID'"`
}

func (n *Novel) NovelAdd(db *gorm.DB) error {
	return db.Debug().Create(n).Error
}

func (n *Novel) FindNovelByTitle(db *gorm.DB, title string) error {
	return db.Debug().Where("title=?", title).First(n).Error
}

func (n *Novel) NovelUpdate(db *gorm.DB, title string) error {
	return db.Debug().Where("title=?", title).Updates(n).Error
}

func (n *Novel) NovelList(db *gorm.DB, in *shuqirpc.NovelListRequest, lists []*shuqirpc.NovelList) ([]*shuqirpc.NovelList, error) {
	/*
		SELECT
		novels.id as novel_id,
		novels.title,
		novels.content,
		novels.class,
		users.id as user_id
		FROM
		novels
		LEFT JOIN users ON novels.user_id=users.id
	*/
	err := db.Debug().Table("novels").
		Select("novels.id as novel_id,novels.title,novels.content,novels.class,users.id as user_id").
		Joins("LEFT JOIN users ON novels.user_id=users.id").
		Scopes(Paginate(int(in.Page), int(in.Size))).Find(&lists).Error
	return lists, err
}
